<template>
  <div ref="containerRef" class="canvas-container">
    <div ref="workspaceRef" class="workspace">
      <div class="inside-shadow"></div>
      <canvas ref="canvasRef" id="fabric-canvas" :class="{ 'with-ruler': showRuler }"></canvas>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, defineEmits } from 'vue';
// @ts-ignore
import { fabric } from 'fabric';

// 定义 emit 函数
const emit = defineEmits(['canvas-ready', 'zoom-changed']);

// 引用DOM元素
const containerRef = ref<HTMLElement | null>(null);
const workspaceRef = ref<HTMLElement | null>(null);
const canvasRef = ref<HTMLCanvasElement | null>(null);

// 画布实例
const canvas = ref<fabric.Canvas | null>(null);

// 设置
const showRuler = ref(true);
const zoomRatio = ref(0.85); // 缩放比例

// 初始化画布
function initCanvas() {
  if (!canvasRef.value) {
    console.error('Canvas DOM element not found');
    return;
  }

  // 创建canvas实例
  canvas.value = new fabric.Canvas(canvasRef.value, {
    fireRightClick: true, // 启用右键
    stopContextMenu: true, // 禁止默认右键菜单
    preserveObjectStacking: true, // 选中对象不会自动置顶
    controlsAboveOverlay: true, // 控制点在遮罩层之上
  });

  // 初始化标尺
  if (showRuler.value) {
    initRulers();
  }

  // 初始化工作区
  initWorkspace();

  // 绑定事件
  bindEvents();

  console.log('Canvas initialized successfully in FabricEditor');
  
  // 关键：在画布完全准备好后触发事件，并将画布实例传递给父组件
  emit('canvas-ready', canvas.value);
}

// 初始化工作区域
function initWorkspace() {
  if (!canvas.value || !workspaceRef.value) return;

  const containerWidth = workspaceRef.value.clientWidth;
  const containerHeight = workspaceRef.value.clientHeight;

  // 设置画布大小为容器大小
  canvas.value.setWidth(containerWidth);
  canvas.value.setHeight(containerHeight);

  // 创建默认工作区矩形
  const workspace = new fabric.Rect({
    width: 800,
    height: 600,
    fill: 'white',
    id: 'workspace',
    strokeWidth: 0,
    selectable: false,
    hasControls: false,
    hoverCursor: 'default',
  });

  canvas.value.add(workspace);
  centerCanvas();

  console.log('Workspace initialized with size:', workspace.width, 'x', workspace.height);
}

// 画布居中显示
function centerCanvas() {
  if (!canvas.value) return;
  
  const zoom = getAutoZoomRatio();
  const center = canvas.value.getCenter();
  
  // 重置视图变换
  canvas.value.setViewportTransform(fabric.iMatrix.concat());
  
  // 居中并应用缩放
  const finalZoom = zoom * zoomRatio.value;
  canvas.value.zoomToPoint(
    new fabric.Point(center.left, center.top),
    finalZoom
  );
  
  // 触发缩放变化事件
  emit('zoom-changed', finalZoom);
  
  // 设置剪切区域
  const workspace = getWorkspace();
  if (workspace) {
    setCenterFromObject(workspace);
  }
  
  canvas.value.renderAll();
  
  logCoordinateInfo();
  console.log('Canvas has been centered, workspace center aligned with container center');
  console.log('Container size:', workspaceRef.value?.clientWidth, 'x', workspaceRef.value?.clientHeight, 
    ', Canvas size:', canvas.value.getWidth(), 'x', canvas.value.getHeight());
}

// 获取工作区对象
function getWorkspace() {
  return canvas.value?.getObjects().find((item: fabric.Object) => item.id === 'workspace') as fabric.Rect | undefined;
}

// 根据对象设置画布中心
function setCenterFromObject(obj: fabric.Object) {
  if (!canvas.value) return;
  
  const objCenter = obj.getCenterPoint();
  const viewportTransform = canvas.value.viewportTransform;
  if (!viewportTransform || canvas.value.width === undefined || canvas.value.height === undefined) return;

  viewportTransform[4] = canvas.value.width / 2 - objCenter.x * viewportTransform[0];
  viewportTransform[5] = canvas.value.height / 2 - objCenter.y * viewportTransform[3];
  
  canvas.value.setViewportTransform(viewportTransform);
}

// 获取自适应缩放比例
function getAutoZoomRatio() {
  const workspace = getWorkspace();
  if (!workspace || !workspaceRef.value) return 1;
  
  return fabric.util.findScaleToFit(workspace, {
    width: workspaceRef.value.offsetWidth,
    height: workspaceRef.value.offsetHeight
  });
}

// 放大
function zoomIn() {
  if (!canvas.value) return;
  
  let zoom = canvas.value.getZoom();
  zoom += 0.05;
  
  const center = canvas.value.getCenter();
  canvas.value.zoomToPoint(new fabric.Point(center.left, center.top), zoom);
  
  // 触发缩放变化事件
  emit('zoom-changed', zoom);
}

// 缩小
function zoomOut() {
  if (!canvas.value) return;
  
  let zoom = canvas.value.getZoom();
  zoom -= 0.05;
  
  const center = canvas.value.getCenter();
  canvas.value.zoomToPoint(
    new fabric.Point(center.left, center.top),
    zoom < 0 ? 0.01 : zoom
  );
  
  // 触发缩放变化事件
  emit('zoom-changed', zoom < 0 ? 0.01 : zoom);
}

// 1:1 显示
function zoomToActualSize() {
  if (!canvas.value) return;
  
  const center = canvas.value.getCenter();
  const zoom = 1; // Set exactly to 1 for true original size
  canvas.value.zoomToPoint(new fabric.Point(center.left, center.top), zoom);
  console.log("5=================zoomToActualSize", zoom);
  
  // 触发缩放变化事件
  emit('zoom-changed', zoom);
}

// 初始化标尺
function initRulers() {
  // 实现简化版标尺，仅用于演示
  // 实际项目中可以引入完整的标尺实现
  console.log('Rulers initialized');
}

// 绑定事件
function bindEvents() {
  if (!canvas.value) return;
  
  // 添加鼠标滚轮缩放功能
  canvas.value.on('mouse:wheel', function(opt: any) {
    const delta = opt.e.deltaY;
    let zoom = canvas.value!.getZoom();
    zoom *= 0.999 ** delta;
    
    // 限制缩放范围
    if (zoom > 20) zoom = 20;
    if (zoom < 0.01) zoom = 0.01;
    
    const center = canvas.value!.getCenter();
    canvas.value!.zoomToPoint(new fabric.Point(center.left, center.top), zoom);
    
    // 触发缩放变化事件，通知父组件更新缩放值
    emit('zoom-changed', zoom);
    
    opt.e.preventDefault();
    opt.e.stopPropagation();
  });
  
  // 窗口大小变化时调整画布
  window.addEventListener('resize', resizeCanvas);
}

// 调整画布大小
function resizeCanvas() {
  if (!canvas.value || !workspaceRef.value) return;
  
  const containerWidth = workspaceRef.value.clientWidth;
  const containerHeight = workspaceRef.value.clientHeight;
  
  canvas.value.setWidth(containerWidth);
  canvas.value.setHeight(containerHeight);
  
  centerCanvas();
}

// 测试添加矩形
function addTestRectangle(options = {}) {
  if (!canvas.value) return;
  
  const rect = new fabric.Rect({
    left: 100,
    top: 100,
    width: 100,
    height: 100,
    fill: 'red',
    ...options
  });
  
  canvas.value.add(rect);
  canvas.value.setActiveObject(rect);
  canvas.value.renderAll();
  return rect;
}

// 设置画布大小
function setCanvasSize(width: number, height: number) {
  if (!canvas.value) return;
  console.log('DEBUG=================');
  const workspace = getWorkspace();
  if (!workspace) return;
  
  workspace.set({
    width,
    height
  });
   console.log('DEBUG=================222');
  // 更新剪裁区域
  workspace.clone((cloned: fabric.Rect) => {
    if (canvas.value) {
      canvas.value.clipPath = cloned;
      canvas.value.requestRenderAll();
    }
  });
  
  centerCanvas();
  console.log(`11111111111Canvas size set to ${width}×${height}`);
}

// 输出坐标信息用于调试
function logCoordinateInfo() {
  if (!canvas.value || !workspaceRef.value) return;
  
  const zoom = canvas.value.getZoom();
  const workspace = getWorkspace();
  if (!workspace) return;
  
  const canvasCenter = canvas.value.getCenter();
  const containerCenter = {
    left: workspaceRef.value.clientWidth / 2,
    top: workspaceRef.value.clientHeight / 2
  };
  
  const viewportTransform = canvas.value.viewportTransform || fabric.iMatrix;
  const origin = {
    x: -viewportTransform[4] / viewportTransform[0],
    y: -viewportTransform[5] / viewportTransform[3]
  };
  
  console.log("---------坐标系统信息---------");
  console.log('缩放比例:', zoom.toFixed(2));
  console.log('画布尺寸:', `${workspace.width as number}×${workspace.height as number}`);
  console.log('容器尺寸:', `${workspaceRef.value.clientWidth}×${workspaceRef.value.clientHeight}`);
  console.log('画布左上角(0,0)在屏幕上的位置:', `(${-viewportTransform[4].toFixed(0)}, ${-viewportTransform[5].toFixed(0)})`);
  console.log('画布中心在屏幕上的位置:', `(${canvasCenter.left.toFixed(0)}, ${canvasCenter.top.toFixed(0)})`);
  console.log('容器中心在屏幕上的位置:', `(${containerCenter.left.toFixed(0)}, ${containerCenter.top.toFixed(0)})`);
  console.log('画布中心与容器中心偏差:', `X=${(canvasCenter.left - containerCenter.left).toFixed(2)}, Y=${(canvasCenter.top - containerCenter.top).toFixed(2)}`);
  console.log('显示模式:', '居中显示');
  console.log("---------调试信息结束---------");
}

// 组件挂载
onMounted(() => {
  // 使用nextTick确保DOM已渲染
  nextTick(() => {
    try {
      initCanvas();
      // 添加测试矩形用于验证画布功能
      // addTestRectangle();
    } catch (err) {
      console.error('Error initializing canvas:', err);
    }
  });
});

// 组件卸载
onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener('resize', resizeCanvas);
  
  // 销毁画布
  if (canvas.value) {
    canvas.value.dispose();
    canvas.value = null;
  }
});

// 暴露给父组件的方法
defineExpose({
  canvas,
  centerCanvas,
  zoomIn,
  zoomOut,
  zoomToActualSize,
  addTestRectangle,
  logCoordinateInfo,
  setCanvasSize
});
</script>

<style scoped>
.canvas-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background-color: #f0f0f0;
}

.workspace {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.inside-shadow {
  position: absolute;
  width: 100%;
  height: 100%;
  box-shadow: inset 0 0 9px 2px rgba(0, 0, 0, 0.12);
  z-index: 2;
  pointer-events: none;
}

#fabric-canvas {
  border: 1px solid #ddd;
}

.with-ruler {
  background-image: linear-gradient(
      45deg,
      #dedcdc 25%,
      transparent 0,
      transparent 75%,
      #dedcdc 0
    ),
    linear-gradient(45deg, #dedcdc 25%, transparent 0, transparent 75%, #dedcdc 0);
  background-position: 0 0, 16px 16px;
  background-size: 32px 32px;
}
</style> 